package com.carryking.smart.rpc.netty.channel;

import com.carryking.smart.rpc.RemoteServiceRepository;
import com.carryking.smart.rpc.entity.ResponseEntity;
import com.carryking.smart.rpc.entity.ResponseFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by jincarry on 2018/1/10.
 */
@Slf4j
public class ClientChannel extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("响应返回:{}",msg);
        }
        if (msg instanceof ResponseEntity) {
            ResponseEntity responseEntity = (ResponseEntity) msg;
            ResponseFuture responseFuture = RemoteServiceRepository.get(responseEntity.getRequestId());
            if (responseFuture == null) {
                throw new RuntimeException("error to get request future");
            }
            responseFuture.complete(responseEntity);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel().close();
        cause.printStackTrace();
    }
}
